package tsli.acm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import tsli.acm.dao.GAAgentStructureDAO;
import tsli.acm.dao.GACommissionNegativeDAO;
import tsli.acm.dao.SFCCommissionPositiveDAO;
import tsli.acm.database.Database;
import tsli.acm.model.GAAgentStructure;
import tsli.acm.model.SFCCommissionPositive;


public class ACM1103Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public ACM1103Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		} else if (request.getParameter("process_type").equals("calFA")) {
			getFA(request, response);
		}else if (request.getParameter("process_type").equals("getDataDetailTable")){
			getDataDetailTable(request, response);
		}

	}
    
    @SuppressWarnings("unchecked")
    private void getDataTable (HttpServletRequest request, HttpServletResponse response) throws IOException {
    	// columns for sorting data
    	int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
    	int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
    	String vaDraw = request.getParameter("sEcho");
    	String vaPeNo = request.getParameter("sSearch_0").trim();
    	String vaYear = request.getParameter("sSearch_1").trim();

    	// get data from database
    	int vnTotal = 0;
    	int vnTotalAfterFilter = 0;
    	List<Map<String, String>> voResult =  new ArrayList<Map<String, String>>();


    	Database db = new Database();
    	GAAgentStructureDAO voGAAgentStructure = new GAAgentStructureDAO(db);
    	List<Map<String, Object>> vaAVPInfo = null;
    	
    	if(!vaYear.equals("")){
    		vaAVPInfo = voGAAgentStructure.findAVPData(vaPeNo);
    	}
    	
    	try {
    		if(vaAVPInfo != null){
    			vnTotal = vaAVPInfo.size();
        		if (vnAmount == -1) {
        			for (int i = 0; i < vaAVPInfo.size(); i++) {

        				Map<String, String> voTmp = new HashMap<String, String>();
        				voTmp.put("PE_NO", vaAVPInfo.get(i).get("PE_NO").toString());
        				voTmp.put("TITLE_NAME", vaAVPInfo.get(i).get("NM_TITLE_THAI").toString());
        				voTmp.put("NAME", vaAVPInfo.get(i).get("NM_THAI").toString());
        				voTmp.put("SURNAME", vaAVPInfo.get(i).get("SURNM_THAI").toString());
        				voResult.add(voTmp);
        			}
        		    vnTotalAfterFilter = vnTotal;
        		} else {
        			if (vaAVPInfo.size() != 0) {
        				for (int i = vnStart; i < (vnStart + vnAmount); i++) {

        					Map<String, String> voTmp = new HashMap<String, String>();
        					voTmp.put("PE_NO", vaAVPInfo.get(i).get("PE_NO").toString());
            				voTmp.put("TITLE_NAME", vaAVPInfo.get(i).get("NM_TITLE_THAI").toString());
            				voTmp.put("NAME", vaAVPInfo.get(i).get("NM_THAI").toString());
            				voTmp.put("SURNAME", vaAVPInfo.get(i).get("SURNM_THAI").toString());
        					voResult.add(voTmp);
        					if (i == (vaAVPInfo.size() - 1)) 
        						break;
        				}
        			}
        			vnTotalAfterFilter = vnTotal;
        		}
    		}
    	   	
    	} finally {
    		db.close();
    	}  
    	// prepare data to show in dataTable
    	PrintWriter voOut = response.getWriter();
    	db = new Database();
    	// set sequence
    	int[] vnSequence = new int[voResult.size()];
    	for (int i = 1; i <= voResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;
    	try {
    	   	JSONObject voObject = new JSONObject();
    	    JSONArray voListData = new JSONArray();
    	    for (int i = 0; i < voResult.size(); i++) {
    	    	Map<String, String> voTmp = voResult.get(i);	
    			JSONArray voArray = new JSONArray();
    			voArray.add(vnSequence[i]);
    			voArray.add(voTmp.get("PE_NO"));
    			voArray.add((voTmp.get("TITLE_NAME") + " " + voTmp.get("NAME") + " " + voTmp.get("SURNAME")));
    		    // data for button's action
    			
    			
    			GAAgentStructureDAO voGAAgentStructureDAO = new GAAgentStructureDAO(db);
    			GACommissionNegativeDAO voGACommissionNegative = new GACommissionNegativeDAO(db);
    			
    			List<Map<String, Object>> voDataProductionPart = voGAAgentStructureDAO.getPersistencyBonusForAVP(voTmp.get("PE_NO"),vaYear);
				
				double vnPersistencyBonus = 0;
				double vnRYP2_6 = 0;
				double vnBonusRate = 0;
				double vnFreeLook = 0;
				DecimalFormat voDecimalFormat = new DecimalFormat("#,##0.00");
				
				for(int j=0; j<voDataProductionPart.size(); j++){
					vnRYP2_6 += Double.parseDouble(voDataProductionPart.get(j).get("RYP2_6").toString());
					vnBonusRate = Double.parseDouble(voDataProductionPart.get(j).get("BONUS_RATE").toString());
				}
				
				if(voGACommissionNegative.getAVPFreeLook(vaPeNo,vaYear)!=null){
					vnFreeLook = Double.parseDouble(voGACommissionNegative.getAVPFreeLook(vaPeNo,vaYear).get("RYC").toString());
				}else{
					vnFreeLook = 0;
				}

				vnPersistencyBonus = ((vnRYP2_6 - vnFreeLook)*vnBonusRate)/12;
				voArray.add(voDecimalFormat.format(vnPersistencyBonus));
    			
				voArray.add(voTmp.get("PE_NO")+"|"+(voTmp.get("TITLE_NAME") + " " + voTmp.get("NAME") + " " + voTmp.get("SURNAME")));
    			// adding array data into list
    		    voListData.add(voArray);
    		}
    		voObject.put("sEcho", Integer.parseInt(vaDraw));
    		voObject.put("iTotalRecords", vnTotal);
    		voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
    		voObject.put("aaData", voListData);
    		voOut.print(voObject.toJSONString());
    	} finally {
    		db.close();
    		voOut.close();
    	}
    }
    
    public void getDataDetailTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
    	int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
    	String vaDraw = request.getParameter("sEcho");
    	String vaPeNo = request.getParameter("sSearch_0").trim();
    	String vaYear = request.getParameter("sSearch_1").trim();
    	String vaType = request.getParameter("sSearch_2").trim();

    	// get data from database
    	int vnTotal = 0;
    	int vnTotalAfterFilter = 0;
    	List<Map<String, String>> voResult =  new ArrayList<Map<String, String>>();


    	Database db = new Database();
    	GACommissionNegativeDAO voGACommissionNegative = new GACommissionNegativeDAO(db);
    	List<Map<String, Object>> vaGAInfo = null;
    	if(vaType.equals("getFreelookDetail")){
    		vaGAInfo = voGACommissionNegative.getAVPFreeLookDetail(vaPeNo, vaYear);
    	}
    	
    	try {
			if(vaGAInfo!=null){
			    	   	vnTotal = vaGAInfo.size();
			    		if (vnAmount == -1) {
			    			for (int i = 0; i < vaGAInfo.size(); i++) {
			
			    				Map<String, String> voTmp = new HashMap<String, String>();
			    				voTmp.put("CLOS_YM", vaGAInfo.get(i).get("CLOS_YM").toString());
			    				voTmp.put("PE_NO_COL", vaGAInfo.get(i).get("PE_NO_COL").toString());
			    				voTmp.put("PO_NO", vaGAInfo.get(i).get("PO_NO").toString());
			    				voTmp.put("RYC", vaGAInfo.get(i).get("RYC").toString());
			    				voResult.add(voTmp);
			    			}
			    		    vnTotalAfterFilter = vnTotal;
			    		} else {
			    			if (vaGAInfo.size() != 0) {
			    				for (int i = vnStart; i < (vnStart + vnAmount); i++) {
			
			    					Map<String, String> voTmp = new HashMap<String, String>();
			    					voTmp.put("CLOS_YM", vaGAInfo.get(i).get("CLOS_YM").toString());
			        				voTmp.put("PE_NO_COL", vaGAInfo.get(i).get("PE_NO_COL").toString());
			        				voTmp.put("PO_NO", vaGAInfo.get(i).get("PO_NO").toString());
			        				voTmp.put("RYC", vaGAInfo.get(i).get("RYC").toString());
			    					voResult.add(voTmp);
			    					if (i == (vaGAInfo.size() - 1)) 
			    						break;
			    				}
			    			}
			    			vnTotalAfterFilter = vnTotal;
			    		}
			}
    	} finally {
    		db.close();
    	}  
    	
    	DecimalFormat voDecimalFormat = new DecimalFormat("#,##0.00");
    	// prepare data to show in dataTable
    	PrintWriter voOut = response.getWriter();
    	// set sequence
    	int[] vnSequence = new int[voResult.size()];
    	for (int i = 1; i <= voResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;
    	try {
    	   	JSONObject voObject = new JSONObject();
    	    JSONArray voListData = new JSONArray();
    	    for (int i = 0; i < voResult.size(); i++) {
    	    	Map<String, String> voTmp = voResult.get(i);	
    			JSONArray voArray = new JSONArray();
    			voArray.add(vnSequence[i]);
    			voArray.add(voTmp.get("CLOS_YM"));
    			voArray.add(voTmp.get("PE_NO_COL"));
    			voArray.add(voTmp.get("PO_NO"));
    			voArray.add(voDecimalFormat.format(Double.parseDouble(voTmp.get("RYC"))));
    			// adding array data into list
    		    voListData.add(voArray);
    		}
    		voObject.put("sEcho", Integer.parseInt(vaDraw));
    		voObject.put("iTotalRecords", vnTotal);
    		voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
    		voObject.put("aaData", voListData);
    		voOut.print(voObject.toJSONString());
    	} finally {
    			voOut.close();
    	}
    }
    
    public void getFA(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	String vaPeNo = request.getParameter("peNo");
		String vaYear = request.getParameter("year");
    	
    	Database db = new Database();
		GAAgentStructureDAO voGAAgentStructureDAO = new GAAgentStructureDAO(db);
		GACommissionNegativeDAO voGACommissionNegative = new GACommissionNegativeDAO(db);
		
		JSONObject voObject = new JSONObject();
		JSONArray voArray = new JSONArray(); 
		JSONArray voArrayCommission = new JSONArray(); 
		PrintWriter out = response.getWriter();
		
		try {
			if(voGAAgentStructureDAO.getPersistencyBonusForAVP(vaPeNo,vaYear)!=null){
				List<Map<String, Object>> voDataProductionPart = voGAAgentStructureDAO.getPersistencyBonusForAVP(vaPeNo,vaYear);
				
				double vnPersistencyBonus = 0;
				double vnRYP2_6 = 0;
				double vnPersistencyRate = 0;
				double vnBonusRate = 0;
				double vnFreeLook = 0;
				String vaPersistencyLange = "";
				DecimalFormat voDecimalFormat = new DecimalFormat("#,##0.00");
				
				for(int i=0; i<voDataProductionPart.size(); i++){
					vnRYP2_6 += Double.parseDouble(voDataProductionPart.get(i).get("RYP2_6").toString());
					vnPersistencyRate = Double.parseDouble(voDataProductionPart.get(i).get("PERSISTENCY_RATE").toString());
					vaPersistencyLange = voDataProductionPart.get(i).get("PERSISTENCY_RATE_LANGE").toString();
					vnBonusRate = Double.parseDouble(voDataProductionPart.get(i).get("BONUS_RATE").toString());
					voArrayCommission.add(voDecimalFormat.format(Double.parseDouble(voDataProductionPart.get(i).get("RYP2_6").toString()))
											+"|"+voDataProductionPart.get(i).get("STATUS").toString());
				}
				
				if(voGACommissionNegative.getAVPFreeLook(vaPeNo,vaYear)!=null){
					vnFreeLook = Double.parseDouble(voGACommissionNegative.getAVPFreeLook(vaPeNo,vaYear).get("RYC").toString());
				}else{
					vnFreeLook = 0;
				}
				
				
				voObject.put("freelook", voDecimalFormat.format(vnFreeLook));
				voObject.put("ryp2_6",voDecimalFormat.format(vnRYP2_6));
				voObject.put("remain_bonus", voDecimalFormat.format(vnRYP2_6 - vnFreeLook));
				
				voObject.put("persistency_rate",voDecimalFormat.format(vnPersistencyRate));
				voObject.put("persistency_lange",vaPersistencyLange);
				voObject.put("bonus_rate",voDecimalFormat.format(vnBonusRate*100));
				voObject.put("commission", voArrayCommission);
				voObject.put("persistency_bonus",voDecimalFormat.format((vnRYP2_6 - vnFreeLook)*vnBonusRate));
				vnPersistencyBonus = ((vnRYP2_6 - vnFreeLook)*vnBonusRate)/12;
				voObject.put("net_persistency_bonus",voDecimalFormat.format(vnPersistencyBonus));
				
				
				
				// AFYP >= 90000
				List<GAAgentStructure> voGAAgentStructureList = new ArrayList<GAAgentStructure>();
				List<Map<String, Object>> voGAAgentStructureResult = voGAAgentStructureDAO.findAVPData(vaPeNo,vaYear);
				
				for (int i = 0; i < 12; i++) {
					
					boolean checkAddObject = false;
					String vaPeNoMM = "";
					String vnYear = "";
					String vnTmpMonth = "";
					GAAgentStructure voGAAgentStructure = new GAAgentStructure();
					
					for(int j=0; j<voGAAgentStructureResult.size(); j++){
						Map<String, Object> voObjectGA = voGAAgentStructureResult.get(j);
						
						String vaClosYM = voObjectGA.get("CLOS_YM").toString();
						String vnMonth = vaClosYM.charAt(vaClosYM.length()-2)+""+vaClosYM.charAt(vaClosYM.length()-1);
						vnYear = vaClosYM.charAt(0)+""+vaClosYM.charAt(1)+""+vaClosYM.charAt(2)+""+vaClosYM.charAt(3);
						vaPeNoMM = voObjectGA.get("PE_NO_MM").toString();
						
						if(i<9){
							vnTmpMonth = "0"+(i+1);
							if(("0"+(i+1)).equals(vnMonth)){

								voGAAgentStructure.setVaPeNoMm( vaPeNoMM);
								voGAAgentStructure.setVaClosYm( voObjectGA.get("CLOS_YM").toString());
								voGAAgentStructure.setVaPeNoBm( voObjectGA.get("AFYP").toString());			
								voGAAgentStructureList.add(voGAAgentStructure);
								
								checkAddObject = true;
							}
						}else{
							vnTmpMonth = ""+(i+1);
							if((""+(i+1)).equals(vnMonth)){

								voGAAgentStructure.setVaPeNoMm( vaPeNoMM);
								voGAAgentStructure.setVaClosYm( voObjectGA.get("CLOS_YM").toString());
								voGAAgentStructure.setVaPeNoBm( voObjectGA.get("AFYP").toString());			
								voGAAgentStructureList.add(voGAAgentStructure);
								
								checkAddObject = true;
							}
						}
					}
					
					if(checkAddObject == false){
						voGAAgentStructure.setVaPeNoMm( vaPeNoMM);
						voGAAgentStructure.setVaClosYm( vnYear+""+vnTmpMonth);
						voGAAgentStructure.setVaPeNoBm( "0");			
						voGAAgentStructureList.add(voGAAgentStructure);
					}

				}
			
				
				
				

				
				
				double vnMonth1 = 0.0, vnMonth2 = 0.0, vnMonth3 = 0.0, vSumAFYP = 0.0;
				String vaPayM1 = "",vaPayM2 = "",vaPayM3 = "";
				
				String vnMonthName[] = {"", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"};
				boolean chkCalFirstMonth = false;
				boolean chkCalSecondMonth = false;
				boolean chkCalThirdMonth = false;
				for (int i = 0; i < voGAAgentStructureList.size(); i++){
					double vnPeNoMM = Double.parseDouble( voGAAgentStructureList.get(i).getVaPeNoMm());
					String vaClosYM = voGAAgentStructureList.get(i).getVaClosYm();
					double vnAFYP = Double.parseDouble( voGAAgentStructureList.get(i).getVaPeNoBm());
					String vnMonth = vaClosYM.charAt(vaClosYM.length()-2)+""+vaClosYM.charAt(vaClosYM.length()-1);
					
					if (vnMonth.equals("01") || vnMonth.equals("04") || vnMonth.equals("07") || vnMonth.equals("10")){
						
						if ( vnAFYP >= 90000 && vnAFYP < 180000){
							vnMonth1 = vnPersistencyBonus;
							vaPayM1 = "จ่าย";
						} else if ( vnAFYP >= 180000 && vnAFYP < 270000){
							vnMonth1 = vnPersistencyBonus;
							vaPayM1 = "จ่าย";
							chkCalSecondMonth = true;
						} else if ( vnAFYP >= 270000){
							vnMonth1 = vnPersistencyBonus;
							vaPayM1 = "จ่าย";
							chkCalSecondMonth = true;
							chkCalThirdMonth = true;
						} else {
							vnMonth1 = 0;
							vaPayM1 = "ไม่จ่าย";
						}
						vSumAFYP +=vnAFYP;
						String vaSumTemp = voDecimalFormat.format(vSumAFYP);

						voArray.add(vnMonthName[Integer.parseInt(vnMonth)]+"|90,000.00|90,000.00|"+voDecimalFormat.format(vnAFYP)+"|"+vaSumTemp+"|"+vaPayM1+"|"+voDecimalFormat.format(vnMonth1)+"|");
					} else if (vnMonth.equals("02") || vnMonth.equals("05") || vnMonth.equals("08") || vnMonth.equals("11")){
						double vnmonth2Total = 0;
						String vamonth2Catchup = "";

						if( vnAFYP >= 90000){
							vnMonth2 = vnPersistencyBonus;
							if ( vnAFYP >= 180000){
								if(vnMonth1 == 0){
									vamonth2Catchup = vnMonthName[Integer.parseInt(vnMonth)-1];
									vnmonth2Total = vnPersistencyBonus*2;

									chkCalFirstMonth = true;
									if ( vnAFYP >= 270000){
										chkCalThirdMonth = true;
									}
								}else{
									vnmonth2Total = vnPersistencyBonus;
									chkCalThirdMonth = true;
								}
								
							}else{
								vnmonth2Total = vnPersistencyBonus;
							}
							vaPayM2 = "จ่าย";
						} else {
							if(chkCalSecondMonth == true){
								vamonth2Catchup = vnMonthName[Integer.parseInt(vnMonth)];
								vnMonth2 = vnPersistencyBonus;
								vnmonth2Total = vnPersistencyBonus;
								vaPayM2 = "จ่าย";
							}else{
								vnMonth2 = 0;
								vaPayM2 = "ไม่จ่าย";
							}
							
						}
						vSumAFYP +=vnAFYP;
						String vaSumTemp = voDecimalFormat.format(vSumAFYP);

						voArray.add(vnMonthName[Integer.parseInt(vnMonth)]+"|90,000.00|180,000.00|"+voDecimalFormat.format(vnAFYP)+"|"+vaSumTemp+"|"+vaPayM2+"|"+voDecimalFormat.format(vnmonth2Total)+"|"+vamonth2Catchup);
					} else if (vnMonth.equals("03") || vnMonth.equals("06") || vnMonth.equals("09") || vnMonth.equals("12")){
				
						double vnmonth3Total = 0;
						String vamonth3Catchup = "";

						if ( vnAFYP >= 90000 ){
							vnMonth3 = vnPersistencyBonus;
							if ( vnAFYP >= 270000){
								if(vnMonth1 == 0 && vnMonth2 == 0){
									vamonth3Catchup = vnMonthName[Integer.parseInt(vnMonth)-1]+","+vnMonthName[Integer.parseInt(vnMonth)-2];
									vnmonth3Total = vnPersistencyBonus*3;
								}else if(vnMonth1 != 0 && vnMonth2 == 0){
									vamonth3Catchup = vnMonthName[Integer.parseInt(vnMonth)-1];
									vnmonth3Total = vnPersistencyBonus*2;
								}else if(vnMonth1 == 0 && vnMonth2 != 0 && chkCalFirstMonth == false){
									vamonth3Catchup = vnMonthName[Integer.parseInt(vnMonth)-2];
									vnmonth3Total = vnPersistencyBonus*2;
								}else{
									vnmonth3Total = vnPersistencyBonus;
								}

							}else{
								vnmonth3Total = vnPersistencyBonus;
							}
							vaPayM3 = "จ่าย";
						} else {
							if(chkCalThirdMonth==true){
								vamonth3Catchup = vnMonthName[Integer.parseInt(vnMonth)];
								vnMonth3 = vnPersistencyBonus;
								vnmonth3Total = vnPersistencyBonus;
								vaPayM3 = "จ่าย";
							}else{
								vnMonth3 = 0;
								vaPayM3 = "ไม่จ่าย";
							}
							
						}
						vSumAFYP +=vnAFYP;
						String vaSumTemp = voDecimalFormat.format(vSumAFYP);

						voArray.add(vnMonthName[Integer.parseInt(vnMonth)]+"|90,000.00|270,000.00.00|"+voDecimalFormat.format(vnAFYP)+"|"+vaSumTemp+"|"+vaPayM3+"|"+voDecimalFormat.format(vnmonth3Total)+"|"+vamonth3Catchup);
						vSumAFYP = 0;
						chkCalFirstMonth = false;
						chkCalSecondMonth = false;
						chkCalThirdMonth = false;
					}
				}		
				
				voObject.put("result", voArray);
				voObject.put("type", "aviable");
				
				out.print(voObject.toJSONString());
				return;
			}else{
				voObject.put("type", "empty");
				
				out.print(voObject.toJSONString());
				return;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			db.close();
		}
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

}
